/* eslint-disable import/no-commonjs */

const path = require('path')
//支持post mock数据
const express = require('express')
//启动expressServer
const expressServer = express()
//返回json数据
const bodyParser = require('body-parser')

expressServer.use(bodyParser.urlencoded({ extended: true }))
expressServer.use(bodyParser.json())
const expressRouter = express.Router()
const fs = require('fs')

expressRouter.route('*/:apiName').all(function(req, res) {
  // console.log(req.params, '=====')
  //db.json数据存储文件，也即假数据存储位置
  fs.readFile(path.resolve(__dirname, 'db.json'), 'utf8', function(err, data) {
    //   console.log(err, 'err')
    if (err) throw err
    var data = JSON.parse(data)
    //当前端口名
    if (data[req.params.apiName]) {
      res.json(data[req.params.apiName])
    } else {
      res.send('no such api name')
    }
  })
})

//expressServer.use(relative,expressRouter);
//relative可以设置请求前添加的路径
expressServer.use(expressRouter)
expressServer.listen(3000, function(err) {
  if (err) {
    console.log(err)
    return
  }
  console.log('Listening at http://localhost:' + 3000 + '\n')
})
